<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 16:16
 */

namespace app\api\controller\v4;

use app\api\controller\v2\Auth;
use app\api\controller\v9\OrdersPay;
use app\common\lib\Orders as OrdersLib;
use app\common\model\Recode;
use think\Db;
use think\Log;

/**
 * 命格线订单相关接口
 * Class Orders
 * @package app\api\controller\v4
 */
class Orders extends Auth
{
    protected $nodel;
    protected $msg;

    public function _initialize()
    {
        parent::_initialize();
        $this->nodel = config('code.nodel');
    }

    /**
     * 订单列表
     * @return \think\response\Json
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $type = input('get.type/d', 0);

        $page = input('get.page/d', 1);

        $uid = $this->user['id'];

        //判断订单是否超时未支付
        check_overtime($uid);

        $RecodeModel = new Recode();

        $orders = (new \app\common\model\Orders())->getUidOrders(['uid' => $uid, 'type' => $type, 'is_del' => $this->nodel, 'page' => $page]);

        //将数据根据创建时间排序
        array_multisort(array_column($orders, 'create_time'), SORT_NUMERIC, SORT_DESC, $orders);

        $data = [];
        //重组订单数据
        if (isset($orders) || !empty($orders))
        {
            foreach ($orders as $k => $v)
            {
                //校准生辰订单数据
                if ($v['gid'] == 1)
                {
                    if ($this->is_apple_pay)
                    {
                        $rec_or_price = $this->apple_goods['rec_goods']['or_prize'];
                        $rec_now_price = $this->apple_goods['rec_goods']['now_prize'];
                    } else
                    {
                        $rec_or_price = $v['or_prize'];
                        $rec_now_price = $v['now_prize'];
                        //商品活动折扣
                        $activeDiscount = active($v['gid']);
                        if ($activeDiscount['discount'] && !$this->is_apple_pay)
                        {
                            $rec_now_price *= $activeDiscount['discount'];
                        }

                    }

                    $data[] = [
                        'type' => 1,
                        'rectification_data' => [
                            'id' => $v['reid'],
                            'start_time' => $v['start_time'],
                            'end_time' => $v['end_time'],
                            'or_prize' => sprintf("%.2f", $rec_or_price),
                            'now_prize' => sprintf("%.2f", $rec_now_price),
                        ],
                        'status' => $v['restatus'],
                        'create_time' => $v['create_time'],
                        'order_id' => $v['order_id'],
                        'trade_type' => $v['trade_type'],
                        'count' => 1,
                        'total_price' => sprintf("%.2f", $v['total_amount'])
                    ];
                }//运势订单数据
                elseif (in_array($v['gid'], [2, 3, 4, 5, 6]))
                {
                    $array = [];
                    $rids_array = explode(',', $v['rids']);
                    foreach ($rids_array as $kk => $vv)
                    {
                        if ($vv)
                        {
                            try
                            {

                                $rname = $RecodeModel->getRecode(['uid' => $this->user['id'], 'id' => $vv]);

                            }
                            catch (\Exception $e)
                            {

                                $rname = [
                                    'id' => $vv,
                                    'name' => '未找到'
                                ];
                                \think\Log::write('异常档案id：' . $vv, 'error', true);
                            }
                        } else
                        {
                            $rname = [
                                'id' => $vv,
                                'name' => '未找到'
                            ];
                        }

                        if ($this->is_apple_pay)
                        {
                            foreach ($this->apple_goods['fortune_day_goods'] as $fortune_day_good)
                            {
                                if ($fortune_day_good['id'] == $v['gid'])
                                {
                                    $day_or_price = $fortune_day_good['or_prize'];
                                    $day_now_price = $fortune_day_good['now_prize'];
                                }
                            }
                        } else
                        {
                            $day_or_price = $v['or_prize'];
                            $day_now_price = $v['now_prize'];
                            //商品活动折扣
                            $activeDiscount = active($v['gid']);
                            if ($activeDiscount['discount'] && !$this->is_apple_pay)
                            {
                                $day_now_price *= $activeDiscount['discount'];
                            }
                        }


                        $array[] = [
                            'id' => $rname['id'],
                            'gid' => $v['gid'],
                            'rname' => $rname['name'],
                            'name' => $v['name'],
                            'start_time' => $v['time'],
                            'end_time' => strtotime($v['expire_time'], $v['time']) - 86400,
                            'or_price' => sprintf("%.2f", $day_or_price),
                            'now_price' => sprintf("%.2f", $day_now_price)
                        ];
                    }
                    $data[] = [
                        'type' => 2,
                        'fortune_data' => $array,
                        'create_time' => $v['create_time'],
                        'order_id' => $v['order_id'],
                        'status' => $v['status'],
                        'trade_type' => $v['trade_type'],
                        'count' => count($array),
                        'total_price' => sprintf("%.2f", $v['total_amount'])
                    ];

                }//命格线订单数据
                elseif (in_array($v['gid'], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
                {
                    $gname = [];

                    try
                    {

                        $rname = $RecodeModel->getRecode(['uid' => $this->user['id'], 'id' => $v['rid']]);

                    }
                    catch (\Exception $e)
                    {

                        $rname = [
                            'name' => '未找到',
                        ];
                        \think\Log::write('异常档案id：' . $v['rid'], 'error', true);
                    }

                    try
                    {
                        $ogoods = Db::table('app_orders_goods')
                            ->alias('og')
                            ->join('app_goods g', 'og.gid=g.id', 'LEFT')
                            ->field('g.name')
                            ->where(['og.oid' => $v['oid']])
                            ->selectOrFail();

                    }
                    catch (\Exception $e)
                    {

                        \think\Log::write('异常订单id：' . $v['oid'], 'error', true);

                        return show(config('code.error'), '订单异常');
                    }

                    foreach ($ogoods as $i => $g)
                    {
                        $gname[] = $g['name'];
                    }

                    if (in_array($v['status'], [1, 4]))
                    {
                        $line_status = 1;
                    } else
                    {
                        $line_status = $v['status'];
                    }


                    $data[] = [
                        'type' => 3,
                        'acgmap_data' => [
                            'order_name' => '幸运之城',
                            'order_sub_name' => '幸运之城解锁',
                            'order_sub_rname' => $rname['name'],
                            'order_sub_names' => implode(',', $gname),
                        ],
                        'total_price' => sprintf("%.2f", $v['total_amount']),
                        'create_time' => $v['create_time'],
                        'order_id' => $v['order_id'],
                        'status' => $line_status,
                        'trade_type' => $v['trade_type'],
                        'count' => count($ogoods),
                    ];

                }
            }

        }

        // 统计有多少评论
        $total = count($data);
        //获取数据分页信息
        $per_page = 20;// 当前文章评论每页显示数量
        $data_list = getPaginatorData($total, $page, $per_page);

        //获取分页后的数据
        $data_list['data'] = array_slice($data, $data_list['start'], $per_page);
        unset($data_list['start']);
        unset($data_list['end']);

        return show(config('code.success'), '加载成功', $data_list);
    }

    /**
     * 命格线订单详情
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function read()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = request()->param();

        $validate = validate('Orders');

        //验证请求参数
        if ($validate->scene('read')->check($param) !== true)
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $order_id = $param['order_id'];

        //支付客户端判断该订单是否已经支付,若已经支付,但是status=0;就更改status=1
        (new OrdersLib())->validateOrders($order_id);
        //获取订单数据
        try
        {

            $where = ['or.is_del' => 0, 'order_id' => ['eq', $order_id]];
            $orders = Db::table('app_orders')
                ->alias('or')
                ->field('or.uid,og.gid,g.name,g.or_prize,g.now_prize,g.discount,og.rid,or.status,or.order_id,or.total_amount,or.trade_type,or.create_time,or.pay_time,or.return_time')
                ->join('app_orders_goods og', 'or.id=og.oid', 'LEFT')
                ->join('app_goods g', 'og.gid=g.id', 'INNER')
                ->where($where)
                ->selectOrFail();

        }
        catch (\Exception $e)
        {

            return show(config('code.error'), '订单未找到');
        }

        $array = [];
        //重组订单详情数据
        if (!empty($orders))
        {
            foreach ($orders as $order)
            {
                if ($order['uid'] != $this->user['id'])
                {
                    Log::write('非法订单查询：' . json_encode($param, true), 'error', true);
                    return show(config('code.error'), '服务异常，请稍后重试～');
                }
                $array['status'] = $order['status'];
                switch (true)
                {
                    case in_array($order['status'], [1, 4]):
                        $array['desc'] = '您购买的幸运之城相关内容已成功解锁';
                        $array['order'] = [
                            0 => [
                                'name' => '订单创建时间',
                                'value' => date('Y-m-d H:i:s', $order['create_time'])
                            ],
                            1 => [
                                'name' => '订单支付时间',
                                'value' => date('Y-m-d H:i:s', $order['pay_time'])
                            ],
                        ];
                        break;
                    case $order['status'] == 2:
                        $array['desc'] = '24小时之内未付款订单自动关闭~';
                        $array['order'] = [
                            0 => [
                                'name' => '订单创建时间',
                                'value' => date('Y-m-d H:i:s', $order['create_time'])
                            ]
                        ];
                        break;
                    case $order['status'] == 3:
                        $array['desc'] = '您申请的退款已成功退回到您的账户~';
                        $array['order'] = [
                            0 => [
                                'name' => '订单创建时间',
                                'value' => date('Y-m-d H:i:s', $order['create_time'])
                            ],
                            1 => [
                                'name' => '订单退款时间',
                                'value' => date('Y-m-d H:i:s', $order['return_time'])
                            ],
                        ];
                        break;
                    default:
                        $array['desc'] = '您的订单还没有支付~';
                        $array['order'] = [
                            0 => [
                                'name' => '订单创建时间',
                                'value' => date('Y-m-d H:i:s', $order['create_time'])
                            ]
                        ];
                        break;
                }


                if ($order['discount'])
                {
                    $now_price = $order['or_prize'] * $order['discount'];
                } else
                {
                    $now_price = $order['now_prize'];
                }

                //判断是否是applePay
                if ($this->is_apple_pay)
                {
                    foreach ($this->apple_goods['acg_goods'] as $ap)
                    {
                        if ($order['gid'] == $ap['id'])
                        {
                            $or_price = $ap['or_prize'];
                            $now_price = $ap['now_prize'];
                        }
                    }
                } else
                {
                    $or_price = $order['or_prize'];
                    //商品活动折扣
                    $activeDiscount = active($order['gid']);
                    if ($activeDiscount['discount'] && !$this->is_apple_pay)
                    {
                        $now_price *= $activeDiscount['discount'];
                    }
                }

                $array['lines'][] = [
                    'rid' => $order['rid'],
                    'name' => $order['name'],
                    'or_price' => sprintf("%.2f", $or_price),
                    'now_price' => sprintf("%.2f", $now_price),
                ];

                $array['order_id'] = $order['order_id'];

                $array['trade_type'] = $order['trade_type'];

                $array['total_price'] = sprintf("%.2f", $order['total_amount']);
            }

            $array['count'] = count($orders);
        } else
        {
            return show(config('code.error'), '订单不存在');
        }

        return show(config('code.success'), '成功', $array);
    }

    /**
     * 解锁命格线
     * @throws \Exception
     */
    public function pay_unlock()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param['trade_type'] = input('param.trade_type/d', 0);
        $param['openid'] = $openid = input('param.openid/s', '');
        $param['type'] = input('param.type/d', 0);
        $param['rid'] = input('param.rid/d', 0);
        $param['gids'] = $gids = input('param.gids/s', '');

        $this->CheckUnlock($param);
        if ($this->msg)
        {
            Log::write('v4解锁命运之城请求参数有误：' . $this->msg, 'notice', true);
            return show(config('code.error'), $this->msg);
        }

        $validate = validate('Orders');

        if ($validate->scene('v4_pay_unlock')->check($param) !== true)
        {
            return show(config('code.error'), json_encode($validate->getError(), true));
        }
        $trade_type = $param['trade_type'];// 支付方式
        $rid = $param['rid'];// 档案id
        $type = $param['type'];
        $callback_url = input('param.callback_url', '');

        // 打包支付方式
        if ($type == 1)
        {
            $gids = '19';
        }

        $OrderPayModel = new OrdersPay();
        try
        {
            $data = $OrderPayModel->pay_unlock(['order_type' => 5, 'gids' => $gids, 'trade_type' => $trade_type, 'rid' => $rid, 'map_type' => $type, 'openid' => $openid, 'callback_url' => $callback_url]);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), $e->getMessage());
        }

        if ($data['status'] === true)
        {
            return show(config('code.success'), '下单成功', $data['data']);
        } else
        {
            return show(config('code.error'), '下单失败', $data['data']);
        }
    }

    /**
     * 检测下单参数
     * @param $param
     * @return string
     * @throws \Exception
     */
    private function CheckUnlock($param)
    {
        $this->msg = '';
        //若不是支付宝或微信则退出
        if (!in_array($param['trade_type'], [1, 2], true))
        {
            return $this->msg = '未知的支付方式';
        }
        //type 1=>打包,2=>不打包
        if (!in_array($param['type'], [1, 2], true))
        {
            return $this->msg = '缺少信息';
        }
        if (!$param['rid'])
        {
            return $this->msg = '缺少档案';
        }
        //若档案不是该用户的则退出
        $recode = (new \app\common\cachemodel\Recode())->getInfoById($param['rid']);
        if ($recode['uid'] != $this->user['id'])
        {
            return $this->msg = '服务异常';
        }
        //type=>1时,可不传gids
        if ($param['type'] === 2)
        {
            if (!$param['gids'])
            {
                return $this->msg = '缺少商品信息';
            }
            //若购买的商品不是占星地图则退出
            $gids = $param['gids'] ? explode(',', $param['gids']) : [];
            if (array_diff($gids, config('goods.acg_id')))
            {
                return $this->msg = '未知的商品';
            }
        }
        return $this->msg;
    }
}
